package com.zwj.gulimall.product.service.impl;

import com.zwj.gulimall.product.entity.CategoryEntity;
import com.zwj.gulimall.product.service.CategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwj.common.utils.PageUtils;
import com.zwj.common.utils.Query;

import com.zwj.gulimall.product.dao.AttrGroupDao;
import com.zwj.gulimall.product.entity.AttrGroupEntity;
import com.zwj.gulimall.product.service.AttrGroupService;

import javax.annotation.Resource;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Resource
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long category) {
        IPage<AttrGroupEntity> page;
        if (category == 0) {
            page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    new QueryWrapper<AttrGroupEntity>()
            );
        } else {
            String key = (String) params.get("key");
            QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>().eq("catelog_id", category);
            if (StringUtils.isNotBlank(key)) {
                wrapper.and((obj) -> {
                   obj.eq("attr_group_id", key).or().like("attr_group_name", key);
                });
            }
            page = this.page(new Query<AttrGroupEntity>().getPage(params), wrapper);
        }
        return new PageUtils(page);
    }

    @Override
    public List<Long> getCatePath(Long catelogId) {
        CategoryEntity categoryEntity = categoryService.getById(catelogId);
        Long parentCid = categoryEntity.getParentCid();
        List<Long> catePath = new ArrayList<>(3);
        catePath.add(catelogId);
        if (parentCid != null && parentCid != 0) {
            findCatePath(parentCid, catePath);
        }
        Collections.reverse(catePath);
        return catePath;
    }

    private void findCatePath(Long catelogId, List<Long> catePath) {
        if (catelogId != null && catelogId != 0) {
            catePath.add(catelogId);
            CategoryEntity categoryEntity = categoryService.getById(catelogId);
            Long parentCid = categoryEntity.getParentCid();
            findCatePath(parentCid, catePath);
        }
    }

}